import { ComponentInfoType, ComponentsStateType } from ".";

// 获取下一个选中组件的id
export function getNextSelectedId(
  id: string,
  componentList: ComponentInfoType[]
) {
  const visibleComponentList = componentList.filter((c) => !c.isHidden);
  const index = visibleComponentList.findIndex((c) => c.id === id);
  if (index < 0) return "";
  let newSelectedId = "";
  const length = visibleComponentList.length;
  if (length <= 1) {
    // 当前选中是最后一个，无更多组件
    newSelectedId = "";
  } else {
    // 当前选中是最后一个，选上一个
    if (index + 1 === length) {
      newSelectedId = visibleComponentList[index - 1].id;
    } else {
      // 当前选中不是最后一个，选下一个
      newSelectedId = visibleComponentList[index + 1].id;
    }
  }
  return newSelectedId;
}

// 插入新组件
export function insertNewComponent(
  draft: ComponentsStateType,
  newComponent: ComponentInfoType
) {
  const { selectedId, componentList } = draft;
  const index = componentList.findIndex((c) => c.id === selectedId);
  if (index > -1) {
    // 选中组件，插入到后面
    componentList.splice(index + 1, 0, newComponent);
  } else {
    // 未选中任何组件
    componentList.push(newComponent);
  }
  draft.selectedId = newComponent.id;
}
